const config = require('./config');
const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const session = require('koa-session-minimal');
const serve = require('koa-static');
const mount = require('koa-mount');
const cors = require('koa2-cors');

const index = require('./routes/index');
const users = require('./routes/users');
const api = require('./routes/api');

// error handler
onerror(app);

// session
app.use(session({
    key: 'SESSION_ID',
    store: config.store,
    cookie: config.cookie
}));

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(cors());

app.use(serve(__dirname + '/dist'));
const staticKoa = new Koa();
staticKoa.use(serve(__dirname + '/public', { maxAge: 24 * 7 * 60 * 60 }));
app.use(mount('/public', staticKoa));

app.use(views(__dirname + '/views', {
    extension: 'pug'
}));

app.use(views(__dirname + '/views', {
    extension: 'pug'
}));

// logger
app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(api.routes(), api.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
});

module.exports = app;
